#Ui

import wx
import os.path, urllib2, sys
error = []
progress=0

class Ui:
    def __init__(self, parent):
        self.parent = parent
        self.queue = parent.queue
        self.progressGuage = parent.parent.progressGuage

    def logMessage(self, msg):
        self.queue.put(msg)
        wx.WakeUpIdle()

    def downloadProgress(self, progress, status, filename, size):
        if status == 0:
            self.logMessage("Downloading file: '"+filename+"' "+str(size)+"\n")
            self.progressGuage.SetValue(progress)
        elif status == 1:
            if progress > 0:
                self.progressGuage.SetValue(progress)
        elif status == 2:
            self.progressGuage.SetValue(100)
        elif status == -1:
            self.logMessage('Download failed!\n')
        return True

    def download(self, urls, filename):
        """
            Downloads file, it will try all the urls untill one works.
        """

        if os.path.exists(filename):
            self.logMessage(filename+'\n')
            self.logMessage("\nERROR: file already exists\n\n")
            return True

        chunkSize=1024*8
        succeeded=False
        for url in urls:
            try:
                opener = urllib2.build_opener()
                opener.addheaders = [('User-agent', 'Asylum dependencies')]
                u=opener.open(url)
                totalSize = float(u.headers['content-length'])

                sizeString = "%.2f Bytes" % (totalSize * 1.00)
                if totalSize > 1024:
                    sizeString = "%.2f Kb" % (totalSize/1024.00)
                if totalSize > (1048576):
                    sizeString = "%.2f Mb" % (totalSize/1048576.00)
                if totalSize > (1073741824):
                    sizeString = "%.2f Gb ahh!" % (totalSize/1073741824.00)

                if not self.downloadProgress(0, 0, filename, sizeString):
                    return False

                if totalSize > 0:
                    f=open(filename,'w')
                    current=0

                    while current <= totalSize:
                        f.write(u.read(chunkSize))
                        if not self.downloadProgress(int(100.00*(current/totalSize)), 1, file,totalSize):
                            return False
                        current+=chunkSize
                    if not self.downloadProgress(0, 2, file,totalSize):
                        return False

                    f.close()

                u.close()
                succeeded=True
                break

            except urllib2.HTTPError, e:
                if not self.downloadProgress(0, -1, filename,0):
                    return False
                if e.code == 404:
                    errors.append("download error: '"+url+"' not found ( 404 ).")
                elif e.code == 403:
                    errors.append("download error: Cannot access '"+url+"', permission denied ( 403 )")
                else:
                    errors.append("urlib2 error: "+e.code)

        return succeeded







